package net.anzhuo.common.utils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {

	@Autowired
	private RedisTemplate<String, Object> rt;
	
	private static RedisTemplate<String, Object> redisTemplate;
	
	@PostConstruct
	public void init() {
		redisTemplate = rt;
	}
	
	public static void set(String key, Object value) {
		redisTemplate.opsForValue().set(getPrefix()+key, value);
	}
	
	public static void set(String key, Object value, Long timeout) {
		redisTemplate.opsForValue().set(getPrefix()+key, value, timeout, TimeUnit.SECONDS);
	}
	
	public static Object get(String key) {
		return redisTemplate.opsForValue().get(getPrefix()+key);
	}
	
	public static void delete(String key) {
		redisTemplate.delete(getPrefix()+key);
	}
	
	public static void hset(String key, String hashKey, Object value) {
		redisTemplate.opsForHash().put(getPrefix()+key, hashKey, value);
	}
	
	public static void hset(String key, String hashKey, Object value, Long timeout) {
		redisTemplate.opsForHash().put(getPrefix()+key, hashKey, value);
		redisTemplate.expire(getPrefix()+key, timeout, TimeUnit.SECONDS);
	}
	
	public static void hsetAll(String key, Map<String, Object> map) {
		redisTemplate.opsForHash().putAll(key, map);
	}
	
	public static void hsetAll(String key, Map<String, Object> map, Long timeout) {
		redisTemplate.opsForHash().putAll(key, map);
		redisTemplate.expire(getPrefix()+key, timeout, TimeUnit.SECONDS);
	}
	
	public static Map<Object, Object> hgetAll(String key) {
		return redisTemplate.opsForHash().entries(key);
	}
	
	private static String getPrefix() {
		return "gs:";
	}
}
